<?php


namespace app\api\controller\v19;


use app\api\controller\v13\Auth2;
use app\common\cachemodel\MiniDateText;
use app\common\cachemodel\Recode;
use app\common\cachemodel\ZlAstroCalendarGoods;
use app\common\cachemodel\AstroChange as AstroChangeModel;
use app\common\lib\Util;
use think\Env;

/**
 * @version 2.2.0
 * Class AstroCalendar
 * @package app\api\controller\v19
 */
class AstroCalendar extends Auth2
{
    /**
     * 获取某月天象变动信息
     * @throws \Exception
     */
    public function getMonthChange()
    {
        $date = input('date/s', '');
        $timezone = (isset($this->headers['timezone']) && $this->headers['timezone']) ? $this->headers['timezone'] : 8;

        if (!$date)
        {
            return show(config('code.error'), '请求异常');
        }
        // TODO  删除下面的判断 （由于IOS客户端将2025-01 传成了2024-01 此时临时强制修改日期）
        if ($this->headers['app-type'] === 'ios' && $date === '2024-01')
        {
            $date = '2025-01';
        }

        $astroChangeData = (new AstroChangeModel())->getChangeMonthList($date, $timezone);

        $planetsData = config('astrolog.planets_name');
        $signsData = config('astrolog.sign_name');
        $data = [];
        foreach ($astroChangeData as $item)
        {
            $type = 3;
            switch ($item['type'])
            {
                case 1:
                    if ((int)$item['pid'] === 0)
                    {
                        $type = 1; // 太阳换座
                    }
                    $text = explode('|', $planetsData[$item['pid']])[2] . explode('|', $signsData[$item['in_sign_id']])[2];
                    break;
                case 2:
                    $text = explode('|', $planetsData[$item['pid']])[2] . ((int)$item['speed'] === 1 ? '顺' : '逆');
                    break;
                case 3:
                    $text = '日食';
                    break;
                case 4:
                    $text = '月食';
                    break;
                case 5:
                    $type = 2; // 星月
                    $text = '新月';
                    break;
                case 6:
                    $text = '满月';
                    break;
                default:
                    $text = '';
                    break;
            }

            if ($text)
            {
                $time = gmdateModify('Y-m-d H:i:s', strtotime($item['time']), 0, $timezone, false); // 转换回该时区时间
                $day = date('Y-m-d', $time);

                if ($type === 1)
                {
                    $key = 0;
                } elseif ($type === 2)
                {
                    $key = 1;
                } else
                {
                    $key = $time;
                }
                $data[$day][$key] = [
                    'text' => $text
                ];
            }
        }

        $resData = [
            'astro' => [],
            'birthday' => []
        ];

        foreach ($data as $day => $datum)
        {
            ksort($datum);
            $resData['astro'][] = [
                'date' => $day,
                'desc' => current($datum)['text']
            ];
        }

        $recodeData = (new Recode())->userBirthMonthList($this->user, $date, $timezone);
        $tmpArr = [];
        $dateArr = explode('-', $date);//客户端的时间
        $year = current($dateArr);
        //判断客户端的年份是否是闰年
        $is_bissextile = is_bissextile($year);
        foreach ($recodeData as $k => $item)
        {
            $recodeTime = (int)$item['month'] . (int)$item['day'];//档案时间
            if (in_array($recodeTime, $tmpArr))   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            {
                unset($recodeData[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
            } else
            {
                //若客户端当前是平年，则2月29的生日不反回
                if (!$is_bissextile && $item['month'] == 2 && $item['day'] == 29)
                {
                    continue;
                }
                $tmpArr[] = $recodeTime;
                if (Util::CheckAppVersion('2.9.8') !== '小')
                {
                    $monthTmp = sprintf("%'.02d", $item['month']);
                    $dayTmp = sprintf("%'.02d", $item['day']);
                } else
                {
                    $monthTmp = $item['month'];
                    $dayTmp = $item['day'];
                }
                $resData['birthday'][] = [
                    'date' => $year . '-' . $monthTmp . '-' . $dayTmp,//客户端年 + 档案月日
                    'type' => $item['type']
                ];  //将不同的值放在该数组中保存
            }
        }
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取天象详情
     * @return \think\response\Json
     * @throws \Exception
     */
    public function getDayInfo()
    {
        $date = input('date/s', '');
        $timezone = (isset($this->headers['timezone']) && $this->headers['timezone']) ? $this->headers['timezone'] : 8;

        if (!$date)
        {
            return show(config('code.error'), '请求异常');
        }

        $intDate = (int)date('Ymd', strtotime($date));

        $astroChangeModel = new AstroChangeModel();
        // 获取星象变动数据 正在进行中的星象
        $underwayAstro = $astroChangeModel->getChangeDayList($date, $timezone);
        $astroChangeText = [];
        if ($this->user && $this->user['rid'])
        {
            $newIntDate = (int)date('Ymd'); // 今天的日期
            $isSendDingDing = $newIntDate === $intDate; // 是否发送钉钉消息

            $recodeInfo = (new Recode())->getInfoById($this->user['rid']);
            // 通过星象变动数据 获取星象变动词条
            $astroChangeText = $astroChangeModel->getChangeText($date, $timezone, $underwayAstro['listData'], $recodeInfo, $isSendDingDing);
        }

        if (!$astroChangeText)
        {   // 如果没有获取到星象变动词条 则使用 星座寄语 ->获取今天的星座寄语为词条
            $word = (new MiniDateText())->getWord($intDate, 1);
            if (trim($word))
            {
                $astroChangeText[] = [
                    'title' => '每日一语',
                    'content' => $word,
                ];
            }
        }
        // 获取今日天象推荐的商品
        $goods = (new ZlAstroCalendarGoods())->getGoodsToDate($intDate);

        $goodsData = [];
        foreach ($goods as $goodItem)
        {
            $goodsData[] = [
                'good_img' => $goodItem['img'],
                'img_scale' => $goodItem['img_scale'],
                'target' => $goodItem['target'],
                'link' => $goodItem['link'],
            ];
        }
        $recodeData = (new Recode())->userBirthMonthList($this->user, $date, $timezone);
        $birthday_list = [];
        $serverTime = gmdateModify('Y-m-d', time(), 8, (float)$timezone);//当前时区的当前时间
        [$clientYear, $clientMonth, $clientday] = explode('-', $date);//客户端时间
        $host = Env::get('host.domain');
        foreach ($recodeData as $item)
        {
            $avatar = '';
            $text = '';
            $target = null;
            $link = null;
            $btn_text = null;
            $is_birth = false;
            $recodeMonth = (int)$item['month'] . '-' . (int)$item['day'];
            //判断档案是否是本年本月本日的生日，用来领取权益
            if ($serverTime == $date && (int)$clientMonth . '-' . (int)$clientday == $recodeMonth)
            {
                $target = $item['target'];
                $link = $host . $item['link'];
                $btn_text = $item['btn_text'];
            }
            //判断档案是否是本月本日的生日，用来页面显示
            if ((int)$clientMonth . '-' . (int)$clientday == $recodeMonth)
            {
                $avatar = $item['avatar'];
                $text = $item['text'];
                $is_birth = true;
            }
            if ($is_birth)
            {
                $birthday_list[] = [
                    'avatar' => $avatar,
                    'text' => $text,
                    'target' => $target,
                    'link' => $link,
                    'btn_text' => $btn_text,
                ];
            }
        }
        $resData = [
            'underway_astro' => $underwayAstro['resData'],
            'astro_info_list' => $astroChangeText,
            'goods_data' => $goodsData,
            'birthday_list' => $birthday_list
        ];

        return show(config('code.success'), '请求成功', $resData);
    }
}
